import axios, { AxiosResponse } from 'axios';
import { message } from 'antd';

type DataValType = string | number | undefined;
type Method = 'get' | 'GET' | 'post' | 'POST';
type Params = Record<string, DataValType>;
type GetParams = { params: Params };
type AxiosReturnType = Promise<AxiosResponse<string, Params | GetParams>>;

const ajax = (url: string, data: Params = {}, method: Method = 'GET'): Promise<AxiosResponse> => {
    /*  try {
         const promise: AxiosReturnType = ['post', 'POST'].includes(method) ? axios.post(url, data) : axios.get(url, { params: data });
         const response: AxiosResponse = await promise;
         return response;
     } catch (err: unknown) {
         const msg: string = `请求错误: ${(err as Error).message}`;
         message.error(msg);
         return Promise.reject(msg);
     } */
    const promise: AxiosReturnType = ['post', 'POST'].includes(method) ? axios.post(url, data) : axios.get(url, { params: data });
    return promise.catch((err: Error) => {
        const msg: string = `请求错误: ${err.message}`;
        message.error(msg);
        return Promise.reject(msg);
    });
};

export type { AxiosResponse };
export default ajax;